package com.opdar.seed.idoc.auth;

import com.opdar.framework.db.interfaces.IDao;
import com.opdar.framework.db.interfaces.IDatabase;
import com.opdar.framework.web.SeedWeb;
import com.opdar.framework.web.anotations.Component;
import com.opdar.framework.web.anotations.Inject;
import com.opdar.seed.extra.utils.StringUtils;
import com.opdar.seed.extra.utils.crypto.MD5;
import com.opdar.seed.extra.utils.crypto.SHA1;
import com.opdar.seed.idoc.base.TemplateView;
import com.opdar.seed.idoc.beans.UsersEntity;
import com.opdar.seed.idoc.utils.CacheUtils;
import org.slf4j.Logger;

import java.io.UnsupportedEncodingException;
import java.sql.Timestamp;
import java.util.Random;
import java.util.UUID;

/**
 * Created by 俊帆 on 2015/8/25.
 */

@Component
public class AuthUtils {

    @Inject
    IDatabase database;

    private static byte[] aesKey;

    static {
        try {
            aesKey = "12345678".getBytes("utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    @Inject
    private Logger logger;

    public String login(String userName, String userPwd) {
        UsersEntity entity = findByUserName(userName);
        if (entity != null) {
            logger.info(entity.toString());
            String pwd = getPassword(userPwd, entity.getSalt());
            logger.info("login aes pwd [{}]", pwd);
            if (entity.getUserPwd().equals(pwd)) {
                String token = UUID.randomUUID().toString();
                CacheUtils.cache(entity.getId(), token, 60 * 30);
                return token;
            }
        }
        return null;
    }

    public String getToken() {
        Object token = SeedWeb.SharedRequest().get().getSession().getValue("token");
        if (token != null) return token.toString();
        return null;
    }

    public UsersEntity regist(String userName, String userPwd) {
        UsersEntity user = new UsersEntity();
        String salt = UUID.randomUUID().toString();
        if (!StringUtils.isBlank(userPwd) && userPwd.length() > 6) {
            user.setUserPwd(getPassword(userPwd, salt));
            user.setSalt(salt);
        }
        user.setUserName(userName);
        user.setCreateTime(new Timestamp(System.currentTimeMillis()));
        user.setUpdateTime(new Timestamp(System.currentTimeMillis()));
        user.setId(UUID.randomUUID().toString());
        IDao<UsersEntity> userDao = database.getDao(UsersEntity.class);
        boolean ret = userDao.insert(user).end().status() > 0;
        if (ret) {
            return user;
        }
        return null;
    }

    public String oneKeyRegist(String userName) {
        String pwd = String.valueOf(new Random().nextInt(899999) + 100000);

        String md5 = MD5.encrypt(pwd);
        logger.info("One Key Regist pwd md5 [{}]", md5);
        regist(userName, md5);
        return pwd;
    }

    public UsersEntity findById(String id) {
        IDao<UsersEntity> userDao = database.getDao(UsersEntity.class);
        return userDao.select().where("id", id).WhereEND().end().findOne();
    }

    public UsersEntity findByUserName(String userName) {
        IDao<UsersEntity> userDao = database.getDao(UsersEntity.class);
        return userDao.select().where("user_name", userName).WhereEND().end().findOne();
    }

    public String getPassword(String userPwd, String salt) {
        return SHA1.encrypt(userPwd + salt);
    }

    public UsersEntity modifyPwd(String id, String userPwd) {
        IDao<UsersEntity> userDao = database.getDao(UsersEntity.class);
        UsersEntity user = new UsersEntity();
        String salt = UUID.randomUUID().toString();
        if (!StringUtils.isBlank(userPwd) && userPwd.length() > 6) {
            user.setUserPwd(getPassword(userPwd, salt));
            user.setSalt(salt);
        }
        boolean ret = userDao.update(user).where("id", id).WhereEND().end().status() > 0;
        if (ret) {
            return findById(id);
        }
        return null;
    }

    public void logout() {
        Object token = SeedWeb.SharedRequest().get().getSession().getValue("token");
        if (token != null) {
            SeedWeb.SharedRequest().get().getSession().setValue("token", null);
            CacheUtils.remove(token.toString());
        }
        TemplateView.setGlobalVar("isLogin", "false");
    }
}
